package com.weirong.smartvault.backservice.entity_model;

import com.weirong.smartvault.dao.DictRepository;
import com.weirong.smartvault.entity.Dict;
import com.weirong.smartvault.common.tools.spring.context.SpringContextUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 于2017/12/1由 KFEB4 创建 .
 */
public class DictModel {
    private Dict dict;
    private List<DictModel> sons;
    private List<String> marks;
    private DictRepository dictRepository;
    private Boolean opened;
    private Integer lv;
    public DictModel(Dict dict, String marks) {
        this.dict = dict;
        this.dictRepository = SpringContextUtil.getBean(DictRepository.class);
        this.sons = new ArrayList<>();
        this.marks = new ArrayList<>();
        this.opened = false;
        this.lv = 0;
        for (String mark : marks.split(",")) {
            if (mark.length()==0)
                continue;
            if (Integer.parseInt(mark) == dict.getId()) {
                this.opened = true;
            } else {
                this.marks.add(mark);
            }
        }
        if (this.opened) {
            // 添加子类
            List<Dict> ss = dictRepository.findDictByParentId(this.dict.getId());
            for (Dict s : ss) {
                DictModel t = new DictModel(s, marks); //出现循环则会死循环
                this.sons.add(t);
                t.setLv(this.lv+1);
                this.sons.addAll(t.sons); //自动继承子类的子类
            }
        }else{
            this.marks.add(this.dict.getId().toString());
        }
    }
    public String getId(){
        return dict.getId().toString();
    }
    public List<DictModel> getSonDict() {
        return sons;
    }

    public Integer getLv(){
        return this.lv;
    }
    public void setLv(Integer lv){
        this.lv = lv;
        for(DictModel dict:this.getSonDict()){
            if (dict.getLv()<this.lv+1)
                dict.setLv(this.lv+1);
        }
    }
    public String getThisMarks() {
        //获取该词汇的拓展标志
        return String.join(",", marks);
    }

    public Boolean isOpened() {
        return this.opened;
    }

    public String getName() {
        return dict.getName();
    }

    public String getCode() {
        return dict.getCode();
    }

    public String getDescription() {
        return dict.getDescription();
    }

    public List<DictModel> getAllDict(){
        List<DictModel> ld = new ArrayList<>();
        ld.add(this);
        ld.addAll(this.getSonDict());
        return ld;
    }

    public String getRetract(){
        StringBuilder retract = new StringBuilder("&nbsp;&nbsp;");
        for (int i = 0; i <this.lv; i++) {
            retract.append("&nbsp;&nbsp;&nbsp;&nbsp;");
        }
        return retract.toString();
    }
    public Boolean hasSons(){
        List<Dict> list = dictRepository.findDictByParentId(this.dict.getId());
        return list.size()>0;
    }
}
